/* 
//【生成privatekey.pem私钥】
openssl genrsa -out privatekey.pem 1024 
//【生成publickey.pem公钥】
openssl rsa -in privatekey.pem -pubout -out publickey.pem
*/
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

const privatePem = fs.readFileSync(
  path.resolve(__dirname, "../privatekey.pem")
);
const publicPem = fs.readFileSync(path.resolve(__dirname, "../publickey.pem"));
const privatekey = privatePem.toString();
const publickey = publicPem.toString();
// 加密方法
const encrypto = (data, key) => {
  return crypto.publicEncrypt(key, Buffer.from(data));
};
// 解密方法
const decrypto = (data, key) => {
  return crypto.privateDecrypt(key, data);
};
const content = "RSA非对称加密;";
const crypted = encrypto(content, publickey); // 加密用publickey，只能用私钥才能解密
console.log("RSA非对称加密: " + crypted.toString("hex"));
const decrypted = decrypto(crypted, privatekey); //解密用privatekey
console.log("RSA非对称加密解密结果： " + decrypted.toString());
